package com.company.common.core.dao;

import com.company.common.core.entity.BaseEntity;
import com.company.common.core.entity.Page;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Repository
public class BaseDAO extends SqlSessionDaoSupport {
	@Resource
	@Override
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		super.setSqlSessionFactory(sqlSessionFactory);
	}

	@Resource
	private SqlSessionFactory sqlSessionFactory;

	private SqlSession getBatchSession() {
		return sqlSessionFactory.openSession(ExecutorType.BATCH, false);
	}

	@SuppressWarnings("rawtypes")
	public Page pagedQuery(Map parameterMap, int start, int length, String countSqlName, String pageQuerySqlName) {
		Page page = new Page();
		List<?> list = this.getSqlSession().selectList(pageQuerySqlName, parameterMap, new RowBounds(start, length));
		Integer count = this.getSqlSession().selectOne(countSqlName, parameterMap);
		page.setRows(list);
		page.setTotal(count);
		return page;
	}

	public Page pagedQuery(BaseEntity baseEntity, int start, int length, String countSqlName, String pageQuerySqlName) {
		Page page = new Page();
		List<?> list = this.getSqlSession().selectList(pageQuerySqlName, baseEntity, new RowBounds(start, length));
		Integer count = this.getSqlSession().selectOne(countSqlName, baseEntity);
		page.setRows(list);
		page.setTotal(count);
		return page;
	}

	// 批量操作
	public <T> Collection<T> batchInsert(String statementName, Collection<T> collections) {
		SqlSession batchSession = getBatchSession();

		try {
			for (T obj : collections) {
				batchSession.insert(statementName, obj);
			}

			batchSession.commit();// 手动按批次提交

			batchSession.clearCache();// 清理缓存，防止溢出
		} catch (Exception e) {
			e.printStackTrace();
			batchSession.rollback();
			throw new RuntimeException("批量插入报错", e);
		} finally {
			batchSession.close();
		}
		return collections;// 业务需要增加返回值
	}

	// 批量操作
	public <T> void batchUpdate(String statementName, Collection<T> collections) {
		SqlSession batchSession = getBatchSession();

		try {
			for (T obj : collections) {
				batchSession.update(statementName, obj);
			}

			batchSession.commit();// 手动按批次提交

			batchSession.clearCache();// 清理缓存，防止溢出
		} catch (Exception e) {
			e.printStackTrace();
			batchSession.rollback();
			throw new RuntimeException("批量插入报错", e);
		} finally {
			batchSession.close();
		}
	}

}
